package com.example.service.impl;

import com.example.dao.ManagerDao;
import com.example.dao.PermDao;
import com.example.dao.RoleDao;
import com.example.entity.Manager;
import com.example.entity.User;
import com.example.service.AuthService;
import com.example.utils.JwtUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author fyx
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private ManagerDao managerDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private PermDao permDao;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public User login(String username, String password) {
        Manager user = managerDao.findOneByAccount(username);
        SimpleHash hash = new SimpleHash("MD5", password, username + "simpleWoNiu");
        if (user != null && hash.toHex().equals(user.getPassword())) {
            User result = new User();
            result.setUsername(username);
            // 使用jwtUtils生成token，token中不在包含过期时间，交由redis实现
            // token中默认包含创建时间，不同时间登录会生成不同token
            String token = JwtUtils.sign(username);
            result.setToken(token);
            // 将token放入redis进行管理，(username + token)作为键值，实现多个用户端登录，强制下线其余设备
            // 设置过期时间为120分钟
            redisTemplate.opsForValue().set(username+"Token", result,120, TimeUnit.MINUTES);
            return result;
        }
        return null;
    }

    @Override
    public User login2(String username, String password) {
        Manager account = managerDao.findOneByAccount(username);
        if (account != null && account.getPassword().equals(password)) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            return user;
        }
        return null;
    }

    @Override
    @Cacheable("userRolesCache")
    public List<String> getRoles(String username) {
        return roleDao.findRoles(username);
    }

    @Override
    @Cacheable("userPermsCache")
    public List<String> getPerms(List<String> roles) {
        return permDao.findPerms(roles);
    }
}
